/** This is a generic logger class 
 *  @author ChrM */

package info.chrm.helper;

import java.io.*;
import java.util.*;

public class Logger {
   public static final int OUT_CONSOLE = 0;
   public static final int OUT_LOGFILE = 1;
   private int outputType = OUT_CONSOLE;   
   private File logfile = null;
   private FileWriter logWriter = null;
   
   /** C'tor.
    *  @param _outType Output Type (stdout, file, ...) */
   public Logger(String _logfile) {
      System.out.println(
	    "+ Start Logging at [" + (new DateMan().getTime(0)) + "].");

      if(_logfile == null) {
	 this.outputType = OUT_CONSOLE;
	 System.out.println("+ Write logs to STDOUT.");
      }
      else {
	 this.outputType = OUT_LOGFILE;
	 this.logfile = new File(_logfile);
	 if(/*this.logfile.canWrite()*/ true) {
	    System.out.println("+ Write logs to: " + _logfile);
	    try {
	       this.logWriter = new FileWriter(this.logfile, true);
	       this.logWriter.write(
		  "\n-------------- + Start Logging at [" + (new DateMan().getTime(0)) + "]. --------------\n");
	       this.logWriter.flush();
		  
	    } catch (Exception _ex) {
	       System.err.println("*** Can't write logs to: " + _logfile + ". Exception: " + _ex.toString());
	       this.logfile = null;
	       this.outputType = OUT_CONSOLE;
	       System.out.println("+ Writing logs to STDOUT.");
	    }
	 }
	 else {
	    System.err.println("*** Can't write logs to: " + _logfile);
	    this.logfile = null;
	    this.outputType = OUT_CONSOLE;
	    System.out.println("+ Writing logs to STDOUT.");
	    
	 }
      }

   }

   /** Writes a string to defined output */
   public void write(String _output) {
      String tmpOutDate = new DateMan().getTime(0);
      
      if(this.outputType == Logger.OUT_CONSOLE)
	 System.out.println("[" + tmpOutDate + "]: " + _output);
      else if(this.outputType == Logger.OUT_LOGFILE) {
	 try {
	    this.logWriter.write("\n[" + tmpOutDate + "]: " + _output);
	    this.logWriter.flush();
	 } catch (Exception _ex) {}
      }
   }

   /** Writes an error message */
   public void writeError(String _output) {
      String tmpOutDate = new DateMan().getTime(0);
       
      if(this.outputType == Logger.OUT_CONSOLE)
	 System.err.println("[" + tmpOutDate + "] *** [ERROR]: " + _output);
      else if(this.outputType == Logger.OUT_LOGFILE) {
	 try {
	    this.logWriter.write("\n[" + tmpOutDate + "] *** [ERROR]: " + _output);
	    this.logWriter.flush();
	 } catch (Exception _ex) {}
      }
   }
}
